// pages/index/location/adress.js
var App = getApp();
var locateStr = '';
var source = '';//来源
Page({

  /**
   * 页面的初始数据
   */
  data: {
    school:'无法查到您的学校，请手动选择',
    schoolList:[],
    hasSchool:true, //是否有匹配学校列表
    allList:[], //所有定位数据
    province:[],
    city:[],
    value:[0,0],
    currentChose:{},
    showCityList:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    source = '';
    if (options.type){
      source = options.type
    }
    this.setData({
      school: wx.getStorageSync('currentSchool') == '' ? '无法查到您的学校，请手动选择' : wx.getStorageSync('currentSchool')
    })
    this.getSchoolList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // 重新定位
  locateSchool:function(){
    let that = this;
    wx.getSetting({
      success(res) {
        if (typeof (res.authSetting['scope.userLocation']) == 'undefined' || res.authSetting['scope.userLocation']) {//没有授权信息
          wx.getLocation({
            type: 'wgs84',
            success(res) {
              const latitude = res.latitude //纬度
              const longitude = res.longitude //经度
              const accuracy = res.accuracy;
              locateStr = longitude + ',' + latitude;//经度在前，纬度在后
              wx.showLoading({
                title: '定位中',
              })
              wx.setStorageSync('location', locateStr)
              wx.setStorageSync('latitude', latitude);
              wx.setStorageSync('longitude', longitude);
              that.getUserCity();//定位城市
            }, fail() {
              wx.showToast({
                icon:'none',
                title: '定位失败'
              })
            }
          })
        } else if (!res.authSetting['scope.userLocation']) {//授权被拒
          wx.showModal({
            title: '提示',
            content: '定位关闭，是否开启定位？',
            success(res) {
              if (res.confirm) {
                wx.openSetting({
                  success(res) {
                    if (res.authSetting['scope.userLocation']) {
                      that.locateSchool();
                    } else {
                      that.setData({
                        locate: '定位失败'
                      })
                    }
                  }
                })
              } else {
                wx.showToast({
                  icon: 'none',
                  title: '定位失败'
                })
              }
            }
          })
        }
      }
    })
  },

  getUserCity: function ( ) {
    let that = this; 
    wx.request({
      url: App.data.globalAPI + '/search/index/nearestschool',
      data: {
        token: wx.getStorageSync('token'),
        location: locateStr, 
        type: 'gps'
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res2) {
        const nearest = res2.data.data.nearest;
        const floors = res2.data.data.floors;
        var curPageArr = getCurrentPages();
        var page = curPageArr[curPageArr.length - 2]; //上一个页面

        if (res2.data.error == 0) {
          page.setData({
            locate: nearest.name == null ? '无法查到您的学校，请手动选择' : nearest.name
          })
          that.setData({
            school: nearest.name == null ? '无法查到您的学校，请手动选择' : nearest.name
          })
          that.getCityContainList(nearest.city_id)
          wx.setStorageSync('schoolId', nearest.id);
          wx.setStorageSync('mallStatus', nearest.buy_status);
          wx.setStorageSync('cityId', nearest.city_id);
          wx.setStorageSync('currentSchool', nearest.name == null ? '无法查到您的学校，请手动选择' : nearest.name);
        } else {
          wx.showToast({
            title: '数据异常，请检查您的定位信息及网络状态稍后再试',
            icon: 'none'
          })
        }
      },complete(){
        wx.hideLoading();
      }
    })
  },

  // 选择学校
  choseSchool:function(e){
    let msg = e.currentTarget.dataset.msg;
    var curPageArr = getCurrentPages();
    var page = curPageArr[curPageArr.length - 2]; //上一个页面
    this.setData({
      school: msg.name
    })
    page.setData({
      locate: msg.name
    })
    wx.setStorageSync('schoolId', msg.id);
    wx.setStorageSync('currentSchool', msg.name);
    wx.request({
      url: App.data.globalAPI + '/mall/goods/getyunbuystatus', //接口地址
      data: {
        token: wx.getStorageSync('token'),
        school_id: wx.getStorageSync('userInfo').school_id ? wx.getStorageSync('userInfo').school_id : wx.getStorageSync('schoolId'),
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        if (res.data.error == 0) {
          wx.setStorageSync('mallStatus', res.data.data.yun_buy_status);
          if (source == 'cloud') {//在云库界面重新定位
            wx.reLaunch({
              url: '/pages/index/mall/mall',
            })
          }else if(source=='index'){
            wx.navigateBack({
              detal: 1
            })
          } else{
            let pageUrl = App.data.globalMall + '/#/index?dev=1&token=' + wx.getStorageSync('token') + '&openid=' + wx.getStorageSync('userInfo').openid + '&address=' + msg.name + '&school_id=' + wx.getStorageSync('schoolId') + '&longitude=' + wx.getStorageSync('longitude') + '&latitude=' + wx.getStorageSync('latitude');
            wx.redirectTo({
              url: '/pages/apply/web_page?url=' + encodeURIComponent(pageUrl)
            })
          } 
        } else {
          wx.showToast({
            title: '数据异常，请检查您的定位信息及网络状态稍后再试',
            icon: 'none'
          })
        }
      }, fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      },
    })
  },

  bindChange:function(e){
    let index = e.detail.value[0];
    let sub = e.detail.value[1];
    var list = this.data.allList;
    let province = this.data.province[index];
    
    if (index != this.data.value[0]) {
      //筛选对应城市
      var cityList = [];
      list.city.forEach((item) => {
        if (item.pid == province.id) {
          cityList.push(item)
        }
      })
      this.setData({
        city: cityList,
        value: [index,0]
      }) 
    } else {
      this.setData({
        value: [index, sub]
      }) 
    }   
  },

  // 确定按钮
  showNewSchoolList:function(){
    let cityId = this.data.value[1];
    let proId = this.data.value[0];
    this.setData({
      showCityList:false,
      currentChose: this.data.city[cityId]
    })
    
    wx.setStorageSync('cityId', this.data.currentChose.id);
    wx.setStorageSync('provinceId', this.data.currentChose.pid);
    this.getCityContainList(this.data.currentChose.id)
  },

  // 选择城市
  onChoseCity:function(){
    var list = this.data.allList;
    var city = [];
    this.setData({
      showCityList: true
    })
    //设置初始省份和城市列表
    if(this.data.province.length==0){
      list.city.forEach((item) => {
        if (item.pid == list.province[0].id) {
          city.push(item)
        }
      })
      this.setData({
        province: list.province,
        city: city
      })
    }

    // 设置初始值
    let cityIndex = 0;
    let pId = 0;
    if(this.data.city.length>0){
      this.data.city.forEach((item, i) => {
        if (item.id == wx.getStorageSync('cityId')) {
          cityIndex = i;
          pId = item.pid;
        }
      })
    }

    list.province.forEach((item, i) => {
      if (item.id == pId) {
        this.setData({
          value: [i, cityIndex]
        })
      }
    })
  },

  // 获取当前城市对应的学校
  getSchoolList: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/search/index/openschool',
      data: {
        token: wx.getStorageSync('token'),
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res2) {
        if (res2.data.error == 0) {
          that.setData({
            allList: res2.data.data
          })
          // 筛选当前城市的学校
          that.getCityContainList(wx.getStorageSync('cityId'))
        }else{
          wx.showToast({
            title: '数据异常，请检查您的定位信息及网络状态稍后再试',
            icon:'none'
          })
        }
      }, fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      },complete() {
        wx.hideLoading();
      }
    })
  },

  // 筛选城市包含的学校
  getCityContainList:function(city_id){
    var list = this.data.allList.school;
    var schoolList = [];

    list.forEach((item)=>{
      if (item.city_id == city_id) {
        schoolList.push(item)
      }
    })

    if (schoolList.length > 0) {//当前城市下 有匹配的学校
      this.setData({
        schoolList: schoolList,
        hasSchool: true, 
      })
    }else{
      this.setData({
        schoolList: [],
        hasSchool: false,
      })
    }
  }
})